package com.mall.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.common.Constant;
import com.mall.common.Result;
import com.mall.exception.MallException;
import com.mall.exception.MallExceptionEnum;
import com.mall.model.po.Cart;
import com.mall.model.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserFilter implements Filter {
    public static User currentUser;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取对象req res session 并设置响应数据格式
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        HttpSession session = request.getSession();
        ObjectMapper objectMapper = new ObjectMapper();
//        获取登录用户
        currentUser =(User) request.getSession().getAttribute(Constant.User.CURRENT_USER);
//       判断是否用户登录，未登录抛出异常
        if (currentUser==null){
            String result =objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_LOGIN));
            response.getWriter().write(result);
            return;
        }else {
//            放行用户
        filterChain.doFilter(request,response);
        }
    }
}
